package cn.ratel.route;

import cn.ratel.kit.JsonKit;
import cn.ratel.route.render.Forward;
import cn.ratel.route.render.NotFound;
import cn.ratel.route.render.Redirect;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

enum DefaultRenders implements RenderProvider.Render {
	JSON {
		@Override
		public void render(HttpServletRequest req, HttpServletResponse res, Object result) {
			String json = JsonKit.toJson(result);
			PrintWriter writer = null;
			try {
				res.setHeader("Pragma", "no-cache");
				res.setHeader("Cache-Control", "no-cache");
				res.setDateHeader("Expires", 0);
				res.setCharacterEncoding("utf-8");
				res.setContentType("application/json");

				writer = res.getWriter();
				writer.write(json);
				writer.flush();
			} catch (IOException e) {
				throw new RuntimeException("render error", e);
			} finally {
				if (writer != null) {
					writer.close();
				}
			}
		}

		@Override
		public Class<?> getSupportType() {
			return void.class;
		}
	},

	REDIRECT {
		@Override
		public void render(HttpServletRequest req, HttpServletResponse res, Object result) {
			Redirect redirect = (Redirect) result;
			try {
				res.sendRedirect(redirect.getUrl());
			} catch (IOException e) {
				throw new RuntimeException("render error", e);
			}
		}

		@Override
		public Class<?> getSupportType() {
			return Redirect.class;
		}
	},

	FORWARD {
		@Override
		public void render(HttpServletRequest req, HttpServletResponse res, Object result) {
			Forward forward = (Forward) result;
			try {
				req.getRequestDispatcher(forward.getUrl()).forward(req, res);
			} catch (ServletException | IOException e) {
				throw new RuntimeException("render error", e);
			}
		}

		@Override
		public Class<?> getSupportType() {
			return Forward.class;
		}
	},

	NOT_FOUND {
		@Override
		public void render(HttpServletRequest req, HttpServletResponse res, Object result) {
			res.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}

		@Override
		public Class<?> getSupportType() {
			return NotFound.class;
		}
	}
}